<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref } from 'vue';

import { Input, Textarea, Select, RadioGroup, CheckboxGroup, DatePicker, Form, FormItem } from 'ant-design-vue';
import { ImageUpload, FileUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';


import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { customerTransferHistoryAdd, customerTransferHistoryInfo, customerTransferHistoryUpdate } from '#/api/hm/customerTransferHistory';
import type { CustomerTransferHistoryForm } from '#/api/hm/customerTransferHistory/model';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<CustomerTransferHistoryForm> = {
  id: undefined,
  customerId: undefined,
  fromStaffId: undefined,
  fromStaffName: undefined,
  toStaffId: undefined,
  toStaffName: undefined,
  storeId: undefined,
  storeName: undefined,
  transferReason: undefined,
  transferType: undefined,
  operatorId: undefined,
  operatorName: undefined,
  transferDate: undefined,
  remark: undefined,
}

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<CustomerTransferHistoryForm>>({
    customerId: [
      { required: true, message: "客户ID不能为空" }
    ],
    fromStaffId: [
      { required: true, message: "原负责员工ID不能为空" }
    ],
    toStaffId: [
      { required: true, message: "新负责员工ID不能为空" }
    ],
    operatorId: [
      { required: true, message: "操作人ID不能为空" }
    ],
    operatorName: [
      { required: true, message: "操作人姓名不能为空" }
    ],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[550px]',
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await customerTransferHistoryInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    }

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value ? customerTransferHistoryUpdate(data) : customerTransferHistoryAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  formData.value = defaultValues;
  resetFields();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 4 }">
      <FormItem label="客户ID" v-bind="validateInfos.customerId">
        <Input v-model:value="formData.customerId" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="原负责员工ID" v-bind="validateInfos.fromStaffId">
        <Input v-model:value="formData.fromStaffId" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="原负责员工姓名" v-bind="validateInfos.fromStaffName">
        <Input v-model:value="formData.fromStaffName" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="新负责员工ID" v-bind="validateInfos.toStaffId">
        <Input v-model:value="formData.toStaffId" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="新负责员工姓名" v-bind="validateInfos.toStaffName">
        <Input v-model:value="formData.toStaffName" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="店铺ID" v-bind="validateInfos.storeId">
        <Input v-model:value="formData.storeId" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="店铺名称" v-bind="validateInfos.storeName">
        <Input v-model:value="formData.storeName" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="迁移原因" v-bind="validateInfos.transferReason">
        <Textarea 
          v-model:value="formData.transferReason" 
          :placeholder="$t('ui.formRules.required')" 
          :rows="4" 
        />
      </FormItem>
      <FormItem label="迁移类型：RESIGNATION-离职迁移，MANUAL-手动调整" v-bind="validateInfos.transferType">
        <Select
          v-model:value="formData.transferType"
          :options="[]"
          :getPopupContainer="getPopupContainer"
          :placeholder="$t('ui.formRules.selectRequired')"
        />
      </FormItem>
      <FormItem label="操作人ID" v-bind="validateInfos.operatorId">
        <Input v-model:value="formData.operatorId" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="操作人姓名" v-bind="validateInfos.operatorName">
        <Input v-model:value="formData.operatorName" :placeholder="$t('ui.formRules.required')" />
      </FormItem>
      <FormItem label="迁移时间" v-bind="validateInfos.transferDate">
        <!-- 需要自行调整参数 -->
        <DatePicker 
          v-model:value="formData.transferDate"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </FormItem>
      <FormItem label="备注" v-bind="validateInfos.remark">
        <Textarea 
          v-model:value="formData.remark" 
          :placeholder="$t('ui.formRules.required')" 
          :rows="4" 
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>

